import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { getStatusMessage } from './status'
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_BASEURL,
  timeout: 5000
})
//请求拦截
service.interceptors.request.use(config => {
  return config
}, err => {
  return Promise.reject(err)
})

//响应拦截
service.interceptors.response.use(res => {
  if (res.data.code === 200) {
    return res.data
  } else {
    ElMessage({
      message: getStatusMessage(res.status),
      type: 'error'
    })
    return Promise.reject(res)
  }
}, err => {
  ElMessage({
    message: getStatusMessage(err.response.status),
    type: 'error'
  })
  return Promise.reject(err)
})

//定义基础响应类型--最外层数据结构
interface BaseResponse<T = any> {
  code: number,
  message: string,
  data: T
}
// 此处相当于二次响应拦截
// 为响应数据进行定制化处理
const requestInstance = <T = any>(config: AxiosRequestConfig): Promise<T> => {
  const conf = config;
  return new Promise((resolve, reject) => {
    service.request<any, AxiosResponse<BaseResponse>>(conf).then((res: AxiosResponse<BaseResponse>) => {
      const data = res.data; // 如果data.code为错误代码返回message信息
      if (data.code != 0) {
        ElMessage({
          message: data.message,
          type: 'error'
        });
        reject(data.message);
      } else {
        ElMessage({
          message: data.message,
          type: 'success'
        }); // 此处返回data信息 也就是 api 中配置好的 Response类型
        resolve(data as T);
      }
    });
  });
};
export function get<T = any, U = any>(config: AxiosRequestConfig, url: string, parms?: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'GET', params: parms });
}
export function post<T = any, U = any>(config: AxiosRequestConfig, url: string, data: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'POST', data: data });
}

export function put<T = any, U = any>(config: AxiosRequestConfig, url: string, parms?: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'PUT', params: parms });
}
export function del<T = any, U = any>(config: AxiosRequestConfig, url: string, data: U): Promise<T> {
  return requestInstance({ ...config, url, method: 'DELETE', data: data });
}
export default service